import { MultiSwitcher } from '@shared/ui/MultiSwitcher'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { lang } from '../model/const/languages'
import { loadLanguage, saveLanguage } from '../model/service/LanguageService'

export const TranslationButton = () => {
  const { i18n } = useTranslation()
  const [selectedIndex, setSelectedIndex] = useState<number>(0)

  useEffect(() => {
    const currentLang = loadLanguage()
    if (currentLang) {
      i18n.changeLanguage(currentLang.toLowerCase())
      const currentIndex = lang.indexOf(currentLang)
      currentIndex !== -1 && setSelectedIndex(currentIndex)
    }
  }, [])

  const handleToggleTranslation = (index: number) => {
    setSelectedIndex(index)
    saveLanguage(lang[index])
    i18n.changeLanguage(lang[index].toLowerCase())
  }

  return (
    <MultiSwitcher items={lang} onClick={handleToggleTranslation} selectedIndex={selectedIndex} />
  )
}
